package com.multysite.quercus;

import java.util.TreeMap;
import java.util.logging.Logger;

import javax.script.CompiledScript;

public class CompileScriptEngine {

	private static final Logger log = Logger
			.getLogger(CompileScriptEngine.class.getName());

	private static MondayScriptingContext context = new MondayScriptingContext();
	private static MondayScriptingEngine engine;
	private static MondayScriptingFactory factory;
	private static TreeMap<String, MondayCompiledScript> treeCache = new TreeMap<String, MondayCompiledScript>();

	static {
		context.setUnicodeSemantics(true);
		context.setIni("unicode.semantics", "on");
		context.setScriptEncoding("UTF-8");
		context.init();
		context.start();
		factory = new MondayScriptingFactory();
		engine = new MondayScriptingEngine(factory, context);
	}

	public static CompiledScript getCompileScript(String appId,
			String contentName, String content) {
		MondayCompiledScript compiledscript = null;
		try {
			String prefix = appId + contentName;
			if (treeCache.containsKey(prefix)) {
				log.warning("------cached-----");
				compiledscript = treeCache.get(prefix);
			} else {
				log.warning("------no cach-----");
				StringBuffer strCompile = new StringBuffer();
				strCompile.append("<?php ob_start();?>");
				strCompile.append(content);
				strCompile.append("<?php return ob_get_contents();?>");
				compiledscript = engine.compile(strCompile.toString());
				treeCache.put(prefix, compiledscript);
			}
		} catch (Exception e) {
			log.warning(e.toString());
		}
		return compiledscript;
	}

	public static CompiledScript getCompileScriptNoCache(String content) {
		MondayCompiledScript compiledscript = null;
		try {
			StringBuffer strCompile = new StringBuffer();
			strCompile.append("<?php ob_start();?>");
			strCompile.append(content);
			strCompile.append("<?php return ob_get_contents();?>");
			compiledscript = engine.compile(strCompile.toString());
		} catch (Exception e) {
			log.warning(e.toString());
		}
		return compiledscript;
	}
}
